package com.design.consumer.p01;

import java.util.LinkedList;

/**
 * 
 * 实现缓冲区
 *
 */
public class Storage {

	/** 缓冲区最大容量 */
	private final int MAX_SIZE = 100;

	/** 缓冲区存储的载体 */
	private LinkedList<Object> list = new LinkedList<>();

	/**
	 * 生产num个产品
	 * 
	 * @param num
	 */
	public void produce(int num) {

		synchronized (list) {
			while (list.size() + num > MAX_SIZE) {
				System.out.println("要生产的数量:" + num + ",库存量:" + list.size() + ",暂时不能生产");
				try {
					list.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			// 生产条件满足情况下，生产num个产品
			for (int i = 0; i < num; i++) {
				list.add(new Object());
			}
			System.out
					.println("生产完成" + num + "个产品,现在的仓储容量:" + list.size() + ",生产线程:" + Thread.currentThread().getName());
			list.notifyAll();

		}

	}

	/**
	 * 消费num个产品
	 * 
	 * @param num
	 */
	public void consume(int num) {
		synchronized (list) {
			// 如果仓储容量不足
			while (list.size() < num) {
				System.out.println("要消费的产品数量:" + num + ",库存量:" + list.size() + ",暂时不能消费");

				try {
					list.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			// 条件满足，开始消费
			for (int i = 0; i < num; i++) {
				list.removeFirst();
			}
			System.out.println("已经消费产品数:" + num + ",库存量:" + list.size() + ",消费线程:" + Thread.currentThread().getName());
			list.notifyAll();
		}

	}

	public LinkedList<Object> getList() {
		return list;
	}

	public void setList(LinkedList<Object> list) {
		this.list = list;
	}
}
